<?php
/**
 * Created by PhpStorm.
 * User: Silent
 * Date: 2018/9/5
 * Time: 11:35
 */
class fileFunAction{
    private $file_url = "test.txt";
    private $file_arr = array();
    public function __construct($url)
    {
        if(isset($url)){
            $this->file_url = $url;
        }
    }
    //读文件
    public function ready()
    {
        if(file_exists( $this->file_url)){
            $fp = fopen($this->file_url,"r");
            $str = "";
            $buffer = 1024;//每次读取 1024 字节
            while(!feof($fp)){//循环读取，直至读取完整个文件
                $str .= fread($fp,$buffer);
            }
            $con = explode(",",$str);
            fclose($fp);//文件关闭
            return $con;
        }
    }
    //写文件
    public function write($str){
            $myfile = $this->getFile("a+");
            $this->addLock($myfile,LOCK_EX);
            fwrite($myfile, $str);
            var_dump($this->ready());
//            file_put_contents($myfile,$txt,LOCK_EX);
            $this->file_close($myfile);//文件关闭
    }
    //关闭流
    public function file_close($file){
        if(isset($file)){
            $this->remLock($file);
            fclose($file);
        }
    }
    //打开流
    public function getFile($str)
    {
        return fopen($this->file_url, $str);
    }
    //添加文加锁

    /**
     * @param $file 文件
     * @param $str 读写锁 LOCK_SH 读锁 和 LOCK_EX 写锁
     */
    public  function addLock($file,$str){
        $lock_result = flock($file,$str);
        if(!$lock_result){
            echo "锁定失败\n";
        }else{
            echo "锁定成功\n";
        }
    }
    //去除文件锁
    public  function  remLock($file){
        if(flock($file,LOCK_UN)){
            echo "解锁成功\n";
        }else{
            echo "解锁失败\n";
        }
    }

    //判断加锁类型
    public function judgeLock(){
        if(is_writable($this->file_url)){
            echo "加了写锁\n";
        }
        if(is_readable($this->file_url)){
            echo "加了读锁\n";
        }
    }
}


$aa = new fileFunAction("test.txt");
var_dump($aa->ready());
//$aa->write(",{10|time|2|哈哈哈|0}");

?>